<template>
  <div ref="homeRef" class="home-carousel">
    <div v-for="item in indicatorListFilter" :key="item.value">
      <component
        :is="item.component"
        :index="activeIndex"
        :data="item.data"
        :id="'page-' + item.value"
        class="page-section"
      />
    </div>
    <div class="home-indicator">
      <div v-for="item in indicatorListFilter" :key="item.value" class="indicator-item">
        <div v-if="item.value === activeIndex" class="indicator-label">
          {{ item.label }}
        </div>
        <div class="indicator-icon" @click="setActiveItem(item.value)">
          <img v-if="item.value === activeIndex" src="@/assets/logo.png" />
          <div v-else class="dot" />
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { getCarouselList, homeDataList, cooperateList } from "@/api/home";
import { serviceList } from "@/api/product";
import { solutionList } from "@/api/scheme";
import { productList } from "@/api/ecology";
import { staffList } from "@/api/about";

import Banner1 from "@/views/pc/home/components/Banner1.vue";
import Banner2 from "@/views/pc/home/components/Banner2.vue";
import Banner3 from "@/views/pc/home/components/Banner3.vue";
import Banner4 from "@/views/pc/home/components/Banner4.vue";
import Banner5 from "@/views/pc/home/components/Banner5.vue";
import Banner6 from "@/views/pc/home/components/Banner6.vue";
import Banner7 from "@/views/pc/home/components/Banner7.vue";

const activeIndex = ref<number>(0);
const indicatorList = ref<Array<any>>([
  { value: 0, label: "业务展示", component: markRaw(Banner1), data: [{}] },
  { value: 1, label: "关于天启明通", component: markRaw(Banner2), data: null },
  { value: 2, label: "", component: markRaw(Banner3), data: null },
  { value: 3, label: "", component: markRaw(Banner4), data: null },
  { value: 4, label: "生态产品", component: markRaw(Banner5), data: null },
  { value: 5, label: "团队介绍", component: markRaw(Banner6), data: null },
  { value: 6, label: "合作伙伴", component: markRaw(Banner7), data: null },
]);

const indicatorListFilter = computed(() => {
  return indicatorList.value.filter((item) => item.data);
});

const homeRef = ref<HTMLElement | null>(null);
let observer: IntersectionObserver | null = null;
let lastScrollTime = 0;

onMounted(() => {
  // 获取Banner1数据
  getCarousel();
  // 获取Banner2数据
  getHomeDataList();
  // 获取Banner3数据
  getService();
  // 获取Banner4数据
  getSolution();
  // 获取Banner5数据
  getProductList();
  // 获取Banner6数据
  getStaffList();
  // 获取Banner7数据
  getCooperateList();

  initIntersectionObserver();
  homeRef.value?.addEventListener("wheel", handleWheel, { passive: false });
});

const initIntersectionObserver = () => {
  observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting && entry.intersectionRatio >= 0.5) {
          const id = entry.target.id.replace("page-", "");
          const newIndex = parseInt(id);
          if (!isNaN(newIndex) && newIndex !== activeIndex.value) {
            activeIndex.value = newIndex;
          }
        }
      });
    },
    {
      threshold: [0, 0.5, 1],
      rootMargin: "0px",
      root: null,
    }
  );

  document.querySelectorAll(".page-section").forEach((section) => {
    observer?.observe(section);
  });
};

const handleWheel = (e: WheelEvent) => {
  if (activeIndex.value != 6) {
    e.preventDefault();
  }
  const now = Date.now();
  // 防抖处理，300ms内只触发一次
  if (now - lastScrollTime < 300) return;
  lastScrollTime = now;

  const direction = e.deltaY > 0 ? "down" : "up";
  if (activeIndex.value == 6 && direction === "down") return;

  // 获取当前有数据的组件索引列表
  const availableIndices = indicatorListFilter.value.map((item) => item.value);
  const currentIndex = availableIndices.indexOf(activeIndex.value);

  if (currentIndex === -1) return; // 当前索引不在可用列表中

  let targetIndex = activeIndex.value;

  if (direction === "down" && currentIndex < availableIndices.length - 1) {
    targetIndex = availableIndices[currentIndex + 1];
  } else if (direction === "up" && currentIndex > 0) {
    targetIndex = availableIndices[currentIndex - 1];
  }

  setActiveItem(targetIndex);
};

const setActiveItem = (index: number) => {
  // 检查目标组件是否存在（有数据）
  const targetItem = indicatorList.value.find((item) => item.value === index);
  if (!targetItem || !targetItem.data) {
    return;
  }

  let temp = <any>document.getElementById("page-" + index);
  if (temp) {
    temp.scrollIntoView({ block: "start", behavior: "smooth" });
    setTimeout(() => {
      activeIndex.value = index;
    }, 300);
  }
};

// 获取轮播图
const getCarousel = () => {
  getCarouselList({ pageNum: 1, pageSize: 100, status: 0 }).then((res: any) => {
    if (res.code === 200 && res.rows && res.rows.length > 0) {
      indicatorList.value[0].data = res.rows;
    }
  });
};

// 获取数据展示列表
const getHomeDataList = () => {
  homeDataList({ pageNum: 1, pageSize: 4, status: 0 }).then((res: any) => {
    if (res.code === 200 && res.rows && res.rows.length > 0) {
      indicatorList.value[1].data = res.rows;
    }
  });
};

// 获取产品服务
const getService = () => {
  serviceList({ displayHome: 1, status: 0 }).then((res: any) => {
    if (res.code === 200 && res.rows && res.rows.length > 0) {
      indicatorList.value[2].data = res.rows[0];
      indicatorList.value[2].label = res.rows[0].name;
    }
  });
};

// 获取解决方案
const getSolution = () => {
  solutionList({ displayHome: 1, status: 0 }).then((res: any) => {
    if (res.code === 200 && res.rows && res.rows.length > 0) {
      indicatorList.value[3].data = res.rows[0];
      indicatorList.value[3].label = res.rows[0].name;
    }
  });
};

// 获取生态产品列表
const getProductList = () => {
  productList({
    pageNum: 1,
    pageSize: 8,
    displayHome: 1,
    status: 0,
  }).then((res: any) => {
    if (res.code === 200 && res.rows && res.rows.length > 0) {
      let list = res.rows.map((item: any) => {
        return {
          ...item,
          cover: item.image ? item.image?.split(",")[0] : "",
        };
      });
      indicatorList.value[4].data = [];
      for (let i = 0; i < list.length / 4; i++) {
        let arr = list.slice(i * 4, (i + 1) * 4);
        indicatorList.value[4].data.push(arr);
      }
    }
  });
};

// 获取团队介绍列表
const getStaffList = () => {
  staffList({ pageNum: 1, pageSize: 12, status: 0 }).then((res: any) => {
    if (res.code === 200 && res.rows && res.rows.length > 0) {
      let list = res.rows;
      if (list.length > 0) list[0].hover = true;
      indicatorList.value[5].data = [];
      for (let i = 0; i < list.length / 4; i++) {
        let arr = list.slice(i * 4, (i + 1) * 4);
        indicatorList.value[5].data.push(arr);
      }
    }
  });
};

// 获取合作伙伴列表
const getCooperateList = () => {
  cooperateList({ pageNum: 1, pageSize: 96, status: 0 }).then((res: any) => {
    if (res.code === 200 && res.rows && res.rows.length > 0) {
      indicatorList.value[6].data = res.rows;
    }
  });
};

onUnmounted(() => {
  observer?.disconnect();
  homeRef.value?.removeEventListener("wheel", handleWheel);
});
</script>
<style lang="scss" scoped>
.home-carousel {
  overflow: hidden;
  scroll-behavior: smooth;
  height: 100vh;
  scroll-snap-type: y mandatory;

  .page-section {
    scroll-snap-align: start;
  }
}
.home-indicator {
  position: fixed;
  top: 50%;
  right: 30px;
  z-index: 999;
  transform: translateY(-50%);
  .indicator-item {
    margin-bottom: 25px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    .indicator-label {
      font-size: 16px;
      color: #fff;
      line-height: 18px;
    }
    .indicator-icon {
      width: 20px;
      display: flex;
      justify-content: center;
      margin-left: 10px;
      cursor: pointer;
      img {
        width: 20px;
        height: 20px;
      }
      .dot {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background-color: rgba(255, 255, 255, 0.5);
      }
    }
  }
}
</style>
